<template>
  <div class="category-selection">
    <!-- 知识领域选择页面 -->
    <div v-if="!selectedCategory" class="category-selection">
      <div class="page-header">
        <h1 class="page-title">🎓 选择学习领域</h1>
        <p class="page-subtitle">选择你感兴趣的知识领域，开启科学学习之旅</p>
      </div>

      <!-- 一级分类 -->
      <div class="categories-section">
        <div class="section-header">
          <h2>📚 知识领域</h2>
          <p>专注于计算机科学与技术相关领域</p>
        </div>
        <div class="categories-grid">
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-placeholder">
            <div class="loading-spinner"></div>
            <p>正在加载知识领域...</p>
          </div>
          
          <!-- 错误状态 -->
          <div v-else-if="error" class="error-state">
            <div class="error-icon">❌</div>
            <h3>加载失败</h3>
            <p>{{ error }}</p>
            <button class="retry-btn" @click="retryFetch">重试</button>
          </div>
          
          <!-- 分类卡片 -->
          <template v-else>
            <div
              v-for="cat in categories"
              :key="cat.id"
              class="category-card"
              @click="selectCategory(cat)"
            >
              <div class="category-icon">{{ cat.icon }}</div>
              <h3 class="category-title">{{ cat.name }}</h3>
              <p class="category-description">{{ cat.description }}</p>
              <div class="category-stats">
                <span class="stat-item">
                  <span class="stat-number">{{ cat.questionCount || 100 }}+</span>
                  <span class="stat-label">题目</span>
                </span>
              </div>
            </div>
            
            <!-- 空状态 -->
            <div v-if="categories.length === 0" class="empty-state">
              <div class="empty-icon">📚</div>
              <h3>暂无知识领域</h3>
              <p>暂时没有可用的知识领域分类</p>
            </div>
          </template>
        </div>
      </div>
    </div>

    <!-- 二级分类选择页面 -->
    <div v-else class="subcategory-selection">
      <div class="page-header">
        <button class="back-btn" @click="goBack">
          <span class="back-icon">←</span>
          返回
        </button>
        <h1 class="page-title">{{ selectedCategory.icon }} {{ selectedCategory.name }}</h1>
        <p class="page-subtitle">选择具体的学习方向，开始深入学习</p>
      </div>

      <div class="subcategories-section">
        <div class="section-header">
          <h2>🎯 学习方向</h2>
          <p>选择你感兴趣的具体学习内容</p>
        </div>
        <div class="subcategories-grid">
          <!-- 加载状态 -->
          <div v-if="subLoading" class="loading-placeholder">
            <div class="loading-spinner"></div>
            <p>正在加载学习方向...</p>
          </div>
          
          <!-- 错误状态 -->
          <div v-else-if="subError" class="error-state">
            <div class="error-icon">❌</div>
            <h3>加载失败</h3>
            <p>{{ subError }}</p>
            <button class="retry-btn" @click="retryFetchSub">重试</button>
          </div>
          
          <!-- 子分类卡片 -->
          <template v-else>
            <div
              v-for="sub in subCategories"
              :key="sub.id"
              class="subcategory-card"
              @click="selectSubCategory(sub)"
            >
              <div class="subcategory-icon">{{ sub.icon }}</div>
              <h3 class="subcategory-title">{{ sub.name }}</h3>
              <p class="subcategory-description">{{ sub.description }}</p>
              <div class="subcategory-meta">
                <span class="meta-item">
                  <span class="meta-icon">📝</span>
                  <span class="meta-text">{{ sub.questionCount || 50 }}+ 题目</span>
                </span>
                <span class="meta-item">
                  <span class="meta-icon">⏱️</span>
                  <span class="meta-text">{{ sub.estimatedTime || '30分钟' }}</span>
                </span>
              </div>
            </div>
            
            <!-- 空状态 -->
            <div v-if="subCategories.length === 0" class="empty-state">
              <div class="empty-icon">🎯</div>
              <h3>暂无学习方向</h3>
              <p>该知识领域下暂时没有可用的学习方向</p>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCategoriesList } from '@/api/categories'

export default {
  name: "CategorySelection",
  props: {
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      categories: [],
      subCategories: [],
      selectedCategory: null,
      error: null,
      subError: null,
      subLoading: false,
      navigationInProgress: false,
    }
  },
  methods: {
    // 获取知识领域分类数据
    async fetchCategories() {
      try {
        this.error = null;
        const response = await getCategoriesList(2); // 传递 level=1 获取知识领域
        if (response && response.data) {
          this.categories = response.data;
        } else {
          // 如果后端接口返回的数据结构不同，可以在这里调整
          this.categories = response || [];
        }
      } catch (error) {
        console.error('获取知识领域分类失败:', error);
        // 接口调用失败，设置错误信息
        this.error = error.message || '获取知识领域分类失败，请检查网络连接或稍后重试';
        this.categories = [];
      }
    },

    // 获取学习方向数据
    async fetchSubCategories(parentId) {
      try {
        this.subError = null;
        this.subLoading = true;
        const response = await getCategoriesList(3, parentId); // 传递 level=2 和 parentId 获取学习方向
        if (response && response.data) {
          this.subCategories = response.data;
        } else {
          // 如果后端接口返回的数据结构不同，可以在这里调整
          this.subCategories = response || [];
        }
      } catch (error) {
        console.error('获取学习方向失败:', error);
        // 接口调用失败，设置错误信息
        this.subError = error.message || '获取学习方向失败，请检查网络连接或稍后重试';
        this.subCategories = [];
      } finally {
        this.subLoading = false;
      }
    },

    // 重试获取知识领域
    async retryFetch() {
      await this.fetchCategories();
    },

    // 重试获取学习方向
    async retryFetchSub() {
      if (this.selectedCategory) {
        await this.fetchSubCategories(this.selectedCategory.id);
      }
    },

    async selectCategory(cat) {
      this.selectedCategory = cat;
      this.selectedSubCategory = null;
      this.subError = null;
      this.subCategories = [];
      
      // 从后端获取学习方向数据
      await this.fetchSubCategories(cat.id);
    },

    selectSubCategory(sub) {
      // 防止重复点击
      if (this.navigationInProgress) {
        return;
      }
      
      this.navigationInProgress = true;
      
      // 为子分类添加categoryId属性，用于路由跳转
      const subCategoryWithParent = {
        ...sub,
        categoryId: this.selectedCategory.id
      };
      
      this.$emit('subcategory-selected', {
        category: this.selectedCategory,
        subCategory: subCategoryWithParent
      });
      
      // 延迟重置导航标志
      setTimeout(() => {
        this.navigationInProgress = false;
      }, 1000);
    },

    goBack() {
      this.selectedCategory = null;
      this.selectedSubCategory = null;
      this.subError = null;
      this.subCategories = [];
    },

    // 初始化数据
    async init() {
      await this.fetchCategories();
    }
  },

  async mounted() {
    await this.init();
  }
}
</script>

<style scoped>
/* 页面容器 */
.category-selection {
  max-width: 1000px;
  margin: 0 auto;
}

/* 页面头部样式 */
.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px 0;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 15px 0;
}

.page-subtitle {
  font-size: 1.2rem;
  color: #7f8c8d;
  margin: 0;
}

/* 区域通用样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  flex-wrap: wrap;
  gap: 15px;
}

.section-header h2 {
  font-size: 2rem;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
}

.section-header p {
  font-size: 1.1rem;
  color: #7f8c8d;
  margin: 0;
  flex: 1;
  text-align: center;
}

/* 知识领域选择页面 */
.categories-section {
  margin-bottom: 40px;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.category-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  animation: fadeInUp 0.6s ease-out forwards;
  opacity: 0;
  transform: translateY(30px);
  cursor: pointer;
}

.category-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

@keyframes fadeInUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.category-card:nth-child(1) { animation-delay: 0.1s; }
.category-card:nth-child(2) { animation-delay: 0.2s; }
.category-card:nth-child(3) { animation-delay: 0.3s; }
.category-card:nth-child(4) { animation-delay: 0.4s; }

.category-icon {
  font-size: 2.5rem;
  margin-bottom: 15px;
  display: block;
}

.category-title {
  font-size: 1.2rem;
  color: #2c3e50;
  margin: 0 0 12px 0;
  font-weight: 600;
}

.category-description {
  font-size: 0.95rem;
  color: #7f8c8d;
  line-height: 1.5;
  margin: 0 0 15px 0;
}

.category-stats {
  display: flex;
  justify-content: space-around;
  gap: 15px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 1.2rem;
  font-weight: 700;
  color: #3b82f6;
}

.stat-label {
  font-size: 0.8rem;
  color: #7f8c8d;
  margin-top: 5px;
}

/* 二级分类选择页面 */
.subcategory-selection {
  max-width: 1000px;
  margin: 0 auto;
}

.subcategories-section {
  margin-bottom: 40px;
}

.subcategories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.back-btn {
  padding: 12px 24px;
  border: 2px solid #e9ecef;
  border-radius: 25px;
  font-size: 1rem;
  color: #3b82f6;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.back-btn:hover {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(59, 130, 246, 0.3);
}

.back-icon {
  font-size: 1.1rem;
}

.subcategory-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  animation: fadeInUp 0.6s ease-out forwards;
  opacity: 0;
  transform: translateY(30px);
  cursor: pointer;
}

.subcategory-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.subcategory-card:nth-child(1) { animation-delay: 0.1s; }
.subcategory-card:nth-child(2) { animation-delay: 0.2s; }
.subcategory-card:nth-child(3) { animation-delay: 0.3s; }
.subcategory-card:nth-child(4) { animation-delay: 0.4s; }
.subcategory-card:nth-child(5) { animation-delay: 0.5s; }
.subcategory-card:nth-child(6) { animation-delay: 0.6s; }

.subcategory-icon {
  font-size: 3rem;
  margin-bottom: 20px;
  display: block;
}

.subcategory-title {
  font-size: 1.3rem;
  color: #2c3e50;
  margin: 0 0 15px 0;
  font-weight: 600;
}

.subcategory-description {
  font-size: 1rem;
  color: #7f8c8d;
  line-height: 1.5;
  margin: 0 0 20px 0;
}

.subcategory-meta {
  display: flex;
  justify-content: space-around;
  gap: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9rem;
  color: #7f8c8d;
}

.meta-icon {
  font-size: 1rem;
}

.meta-text {
  font-weight: 500;
}

/* 加载状态 */
.loading-placeholder {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e9ecef;
  border-radius: 50%;
  border-top-color: #3b82f6;
  animation: spin 1s ease-in-out infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-placeholder p {
  color: #7f8c8d;
  font-size: 1.1rem;
  margin: 0;
}

/* 错误状态 */
.error-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.error-icon {
  font-size: 4rem;
  margin-bottom: 20px;
  display: block;
}

.error-state h3 {
  font-size: 1.5rem;
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.error-state p {
  color: #7f8c8d;
  font-size: 1.1rem;
  margin: 0;
}

.retry-btn {
  padding: 10px 25px;
  border: 2px solid #3b82f6;
  border-radius: 25px;
  font-size: 1rem;
  color: #3b82f6;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.retry-btn:hover {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(59, 130, 246, 0.3);
}

/* 空状态 */
.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 20px;
  display: block;
}

.empty-state h3 {
  font-size: 1.5rem;
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.empty-state p {
  color: #7f8c8d;
  font-size: 1.1rem;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-title {
    font-size: 2rem;
  }

  .page-subtitle {
    font-size: 1rem;
  }

  .section-header {
    flex-direction: column;
    text-align: center;
  }

  .section-header h2 {
    font-size: 1.6rem;
  }

  .categories-grid,
  .subcategories-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 1.8rem;
  }

  .page-subtitle {
    font-size: 0.9rem;
  }

  .category-card,
  .subcategory-card {
    padding: 20px;
  }
}
</style>
